<?php


namespace app\admin\controller;

use think\Exception;

class Explore extends Base
{
    public $fileName = 'faxian.json';

    public function __construct()
    {
        parent::__construct();
    }

    protected function getJsonData()
    {
        $filePath = ROOT_PATH . $this->fileName;
        $data = file_get_contents($filePath);
        $data = json_decode($data, true);
        return $data;
    }

    protected function putJsonData($data)
    {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $filePath = ROOT_PATH . $this->fileName;
        $data = file_put_contents($filePath, $data);
    }

    public function index()
    {
        $param = input();
        $type_id = $param['type_id'];
        $types = db('explore_type')->order('sort', 'asc')->select();
        $type_ids = array_column($types, 'id');
        if (!in_array($type_id, $type_ids)) {
            $type_id = $type_ids[0];
        }
//            dump($currentType);
        $page = intval($param['page']) < 1 ? 1 : $param['page'];
        $limit = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $offset = $limit * ($page - 1);
        $total = db('explore')->where('type_id', $type_id)->count();
        $list = [
            'code' => 1,
            'msg' => '数据列表',
            'page' => $page,
            'pagecount' => ceil($total / $limit),
            'limit' => $limit,
            'total' => $total
        ];
        $list['list'] = db('explore')->alias('e')->join('__EXPLORE_TYPE__ et', 'et.id = e.type_id')->where(
            'e.type_id',
            $type_id
        )->field('e.*,et.name as type_name')->order('e.sort', 'asc')->order('e.time_added', 'desc')->order(
            'e.id',
            'desc'
        )->limit($offset, $limit)->select();

        $this->assign('list', $list['list']);
        $this->assign('total', $list['total']);
        $this->assign('page', $list['page']);
        $this->assign('limit', $list['limit']);
        $param = input();
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);
        $this->assign('types', $types);
        $type = $types[array_search($type_id, $type_ids)];
        $this->assign('type', $type);
        $this->assign('type_id', $type_id);
        return $this->fetch('admin@explore/index');
    }

    public function vodindex()
    {
        $xilie_id = input('xilie_id', 0, 'intval');

        $data = db('explore')->order('sort', 'asc')->order('time_added', 'desc')->order('id', 'desc')->select();
        if (empty($xilie_id) && count($data) > 0) {
            $xilie_id = $data[0]['id'];
            $explore = $data[0];
        } else {
            $explore = db('explore')->where('id', $xilie_id)->find();
        }
        $list = $this->data($xilie_id, true);
//            dump(db('explore_vod')->getLastSql());
        $this->assign('explores', $data);
        $this->assign('explore', $explore);
        $this->assign('xilie_id', $xilie_id);
        $this->assign('list', $list['list']);
        $this->assign('total', $list['total']);
        $this->assign('page', $list['page']);
        $this->assign('limit', $list['limit']);
        $param = input();
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);
        return $this->fetch('admin@explore/vodindex');
    }

    protected function data($xilie_id = 0)
    {
        $param = input();
        if ($xilie_id == 0) {
            $xilie_id = $param['xilie_id'];
        }
        $page = intval($param['page']) < 1 ? 1 : $param['page'];
        $limit = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $offset = $limit * ($page - 1);
        $where = [];
        if (isset($param['keyword'])) {
            $where['v.vod_name'] = ['like', '%' . $param['keyword'] . '%'];
            $this->assign('keyword', $param['keyword']);
        }

        $total = db('explore_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')->where(
            $where
        )->where('explore_id', $xilie_id)->count();
        $list = db('explore_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')
            ->where($where)
            ->where('ev.explore_id', $xilie_id)
            ->order('ev.sort', 'asc')
            ->order('ev.time_added', 'desc')
            ->order('ev.id', 'desc')
            ->limit(
                $offset,
                $limit
            )->select();


        return [
            'code' => 1,
            'msg' => '数据列表',
            'page' => $page,
            'pagecount' => ceil($total / $limit),
            'limit' => $limit,
            'total' => $total,
            'list' => $list
        ];
    }

    public function addInExplore()
    {
        $time = time();
        $data = input();
        $ids = $data['vod_ids'];
        $xilie_id = intval($data['id']);
        if ($xilie_id < 1) {
            $this->error('数据id 出错');
        }
        if (count($ids) < 1) {
            $this->error('没有需要处理的数据');
        }
        $vodIds = db('explore_vod')->where('explore_id', $xilie_id)->column('vod_id');
        $ids = array_diff($ids, $vodIds);
        if (empty($ids)) {
            $this->error('所选数据已经在该主题里面了');
        }
        $insertData = [];
        foreach ($ids as $id) {
            $insertData[] = [
                'vod_id' => $id,
                'explore_id' => $xilie_id,
                'time_added' => $time,
                'sort' => 1
            ];
        }

        $return = db('explore_vod')->insertAll($insertData);
        if ($return !== false) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function del()
    {
        $param = input();
        $ids = $param['ids'];

        if (!empty($ids)) {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = db('explore_vod')->where($where)->delete();
            if ($return !== false) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败！');
            }
        }
        return $this->error('参数错误');
    }

    public function field()
    {
        $param = input();
        $ids = $param['ids'];
        $col = $param['col'];
        $val = $param['val'];
        $tab = $param['tab'];


        if (!empty($ids) && $col === 'sort') {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = db($tab)->where($where)->setField('sort', $val);
            if ($return !== false) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        return $this->error('参数错误');
    }

    public function info()
    {
        if (Request()->isPost()) {
            $param = input('post.');
            $where = [];
            if (isset($param['id'])) {
                $where['id'] = ['neq', $param['id']];
            }
            $exsitData = db('explore')->where($where)->where('type_id', $param['type_id'])->where(
                'name',
                $param['name']
            )->find();
            if (!empty($exsitData)) {
                $this->error('标题已经存在，请修改');
            }
            if ($param['id'] > 0) {
                $return = db('explore')->where('id', $param['id'])->update($param);
            } else {
                unset($param['id']);
                $param['time_added'] = time();
                $return = db('explore')->insert($param);
            }
            if ($return !== false) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }

        $id = input('xilie_id');
        $res = db('explore')->where('id', $id)->find();
        $types = db('explore_type')->where('is_show', 1)->order('sort', 'asc')->select();
        $this->assign('info', $res);
        $this->assign('types', $types);

        return $this->fetch('admin@explore/info');
    }

    public function typeinfo()
    {
        if (Request()->isPost()) {
            $param = input('post.');
            if ($param['id'] > 0) {
                $return = db('explore_type')->where('id', $param['id'])->update($param);
            } else {
                unset($param['id']);
                $param['time_added'] = time();
                $return = db('explore_type')->insert($param);
            }
            if ($return !== false) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }

        $id = input('id');
        $res = db('explore_type')->where('id', $id)->find();
        $this->assign('info', $res);

        return $this->fetch('admin@explore/typeinfo');
    }

    public function deleteExplore()
    {
        $id = input('ids');
        $res = db('explore')->whereIn('id', $id)->delete();
        db('explore_vod')->whereIn('explore_id', $id)->delete();
        if ($res !== false) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function deleteType()
    {
        $id = input('id');

        $count = db('explore')->whereIn('type_id', $id)->count();
        if ($count > 0) {
            $this->error('类别下拥有列表内容，请删除列表内容后再删除类别！');
        }
        $res = db('explore_type')->whereIn('id', $id)->delete();

        if ($res !== false) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function daoru()
    {
        $data = $this->getJsonData();
        $array = [];
        $time = time();
        foreach ($data as $item) {
            if (isset($item['ids']) && count($item['ids']) > 0) {
                foreach ($item['ids'] as $id) {
                    $array[] = [
                        'explore_id' => $item['xilie_id'],
                        'vod_id' => $id,
                        'time_added' => $time
                    ];
                }
            }

            if (isset($item['keywords']) && isset($item['keywords']['actor'])) {
                $where['vod_actor'] = [
                    [
                        ['like', '%,' . $item['keywords']['actor'] . ',%'],
                        ['like', $item['keywords']['actor'] . ',%'],
                        ['like', '%,' . $item['keywords']['actor']],
                    ],
                    'or'
                ];
                $list = db('vod')->where($where)->column('vod_id');
                foreach ($list as $id) {
                    $array[] = [
                        'explore_id' => $item['xilie_id'],
                        'vod_id' => $id,
                        'time_added' => $time
                    ];
                }
            }
        }
        dump($array);
        $return = db('explore_vod')->insertAll($array);
        dump($return);
    }

    public function tuisong()
    {
        if (request()->isPost()) {
            $data = input();
            if (isset($data['id'])) {
                unset($data['id']);
            }
            $vodInfo = db('vod')->field('vod_id,vod_name,vod_play_from,vod_play_url')->where(
                'vod_id',
                $data['vod_id']
            )->find();
            if (empty($vodInfo)) {
                $this->error('没有找到这部电影');
            }
//                if ($data['player'] !== 'moren') {
//                    if (strpos($vodInfo['vod_play_from'], $data['player']) === false) {
//                        $this->error('没有找到这部播放源');
//                    }
//                    $players = explode('$$$', $vodInfo['vod_play_from']);
//                    $vIndex = array_search($data['player'], $players);
//                    if ($vIndex !== false) {
//                        $playUrls = explode('$$$', $vodInfo['vod_play_url']);
//                        $usedPlayUrs = $playUrls[$vIndex];
//                        $usedPlayUrs = explode('#', $usedPlayUrs);
//                        $jujis = [];
//                        foreach ($usedPlayUrs as $playurl) {
//                            list($key, $value) = explode('$');
//                            $jujis[] = trim($key);
//                        }
//                        dump($jujis);
//                        if (!in_array($data['juji'], $jujis)) {
//                            $this->error('没有找到该剧集');
//                        }
//                    } else {
//                        $this->error('该播放源没有m3u8');
//                    }
//                } else {
//                    //TODO 怎么校验;
//
//                }
            //保存到数据库
            $id = db('push')->insertGetId($data);
            $pushInfo = $data;
            $pushInfo['id'] = $id;
            $return = sendJpush($pushInfo);
            if (is_array($return) && $return['http_code'] == 200) {
                db('push')->where('id', $id)->update(
                    [
                        'msg_id' => $return['body']['msg_id'],
                        'sendno' => $return['body']['sendno'],

                    ]
                );
                $this->success('推送成功', null, $return);
            } else {
                $this->error('推送失败！请到推送记录列表中重试！' . json_encode($return));
            }
        } else {
            $vod_id = input('id');
//                $vod_id=2081;
//                dump($vod_id);
            $vodInfo = db('vod')->field('vod_id,vod_name')->where('vod_id', $vod_id)->find();
//                $time = microtime(true);
//                $timeEnd = microtime(true);
//                dump(md5($vodInfo['vod_play_url']));
//                dump($timeEnd-$time);
//                echo "<br/><br/><br/><br/>";
//                dump($vodInfo['vod_play_url']);
            $this->assign('vodInfo', $vodInfo);
            return $this->fetch('admin@explore/tuisong');
        }
    }

    public function m3u8()
    {
        if (request()->post()) {
            $data = input('post.');
            if ($data['id'] < 1) {
                $this->error('数据有误');
            }
            $vodInfo = db('vod')->where('vod_id', $data['id'])->field(
                'vod_id,vod_name,vod_time'
            )->find();
            if (empty($vodInfo)) {
                $this->error('没有找到该影片');
            }
            $exsitData = db('m3u8_setting')->where('vod_id', $data['id'])->find();
//                dump($vodInfo);
            if (empty($exsitData)) {
                //插入
                $insert = [
                    'time_added' => time(),
                    'vod_id' => $data['id'],
                    'delete_start_index' => $data['startIndex'],
                    'number' => $data['ts_number'],
                    'delete_end_index' => $data['ts_offset'],
                ];
                $insertId = db('m3u8_setting')->insertGetId($insert);
                if ($insertId < 1) {
                    $this->error('数据添加失败!');
                } else {
                    db('m3u8_job')->insert(
                        [
                            'vod_id' => $vodInfo['vod_id'],
                            'vod_time' => $vodInfo['vod_time'],
                            'time_added' => time(),
                            'status' => 0,
                            'need_delete' => 1
                        ]
                    );
                    db('vod')->where('vod_id', $vodInfo['vod_id'])->update(['is_cache' => 1]);
                    $this->error('数据添加成功！');
                }
            } else {
                //更新
                db('m3u8_setting')->where('vod_id', $data['id'])->update(
                    [
                        'delete_start_index' => $data['startIndex'],
                        'number' => $data['ts_number'],
                        'delete_end_index' => $data['ts_offset'],
                    ]
                );
                $this->success('更新成功！');
            }
        } else {
            $vod_id = input('id', 0, 'intval');
            if ($vod_id < 1) {
                $this->error('数据有误');
            }
            $vodInfo = db('vod')->where('vod_id', $vod_id)->field(
                'vod_id,vod_name,vod_play_from,vod_play_url'
            )->find();
            if (empty($vodInfo)) {
                $this->error('没有找到该影片');
            }
            //拆分并取得相应的数据
            $playFroms = explode('$$$', $vodInfo['vod_play_from']);

            $playUrlArray = [];
            $fromIndex = array_search('ckm3u8', $playFroms);
            if ($fromIndex !== false) {
                $from = 'ckm3u8';
            } else {
                $fromIndex = array_search('zuidam3u8', $playFroms);
                if ($fromIndex !== false) {
                    $from = 'zuidam3u8';
                }
            }
            // 返回空数据
            if (empty($from)) {
                return '没有找到可用的播放源';
            }
            $playUrlGroup = explode('$$$', $vodInfo['vod_play_url']);
            $playUrls = $playUrlGroup[$fromIndex];
            $playUrlsArray = explode('#', $playUrls);
            $playUrlArray = [];
            foreach ($playUrlsArray as $urlIndex => $playUrl) {
                list($key, $value) = explode('$', $playUrl);
                $playUrlArray = [
                    'key' => trim($key),
                    'value' => trim($value),
                    'from' => $from,
                    'vod_id' => $vodInfo['vod_id'],
                    'vod_name' => $vodInfo['vod_name'],
                ];
                break;
            }


            $m3u8content = file_get_contents($playUrlArray['value']);
            $urlArray = explode('/', $playUrlArray['value']);
            array_pop($urlArray);
            $m3u8contentArray = explode("\n", $m3u8content);
            $m3u8contentArray = array_filter($m3u8contentArray);
            $targetM3u8Url = array_pop($m3u8contentArray);
            $targetM3u8Url = join('/', $urlArray) . '/' . $targetM3u8Url;
            $m3u8content = file_get_contents($targetM3u8Url);
            $baseUrlArray = explode('/', $targetM3u8Url);
            array_pop($baseUrlArray);
            $baseUrl = join('/', $baseUrlArray);
            $m3u8contentArray = explode("\n", $m3u8content);
            $m3u8contentArray = array_filter($m3u8contentArray);
            $startIndex = -1;
            $m3u8contentArray = array_chunk($m3u8contentArray, 100);
            $m3u8contentArray = $m3u8contentArray[0];
            foreach ($m3u8contentArray as $tsKey => $tsItem) {
                if (strpos($tsItem, '#EXTINF') === 0 && $startIndex === -1) {
                    $startIndex = $tsKey;
                }
                if (strpos($tsItem, '.ts') > 0 && (strpos(
                            $tsItem,
                            '#'
                        ) === false)) {
                    $m3u8contentArray[$tsKey] = $baseUrl . '/' . $tsItem;
                } else {
                    unset($m3u8contentArray[$tsKey]);
                }
            }
            $info = [
                'id' => $vodInfo['vod_id'],
                'vod_name' => $vodInfo['vod_name'],
                'startIndex' => $startIndex
            ];
            $setting = db('m3u8_setting')->where('vod_id', $vodInfo['vod_id'])->find();
            if (!empty($setting)) {
                $info['ts_number'] = $setting['number'];
                $info['ts_offset'] = $setting['delete_end_index'];
            }
            $this->assign(
                'info',
                $info
            );
            $this->assign('m3u8contentArray', $m3u8contentArray);
            return $this->fetch('admin@explore/m3u8');
        }
    }

    public function cachesetting()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $xilie_id = $data['xilie_id'];
            $xilieInfo = db('explore')->where('id', $xilie_id)->find();
            if (empty($xilieInfo)) {
                $this->error('数据有误!');
            }
            $ts_number = intval($data['ts_number']);
            $ts_offset = intval($data['ts_offset']);
            if($ts_number<1){
                $this->error('缓存数量小于1，无需设置！');
            }
            db()->startTrans();
            try {
                //保存设置；
                db('explore')->where('id', $xilie_id)->update([
                    'ts_number' => $ts_number,
                    'ts_offset' => $ts_offset
                ]);
                //查询未缓存的电影ID
                $vodIds = db('explore_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')->where('ev.explore_id', $xilie_id)->where('v.is_cache',0)->where('v.vod_id','>',0)->column('v.vod_id');
               if(!empty($vodIds)){
                   foreach ($vodIds as $vodId){
                       //标记缓存
                       $sql= db('vod')->where('vod_id',$vodId)->update(['is_cache'=>1]);
                        //写入任务数据库
                       db('m3u8_job')->insert(
                           [
                               'vod_id' => $vodId,
                               'vod_time' => time(),
                               'time_added' => time(),
                               'status' => 0,
                               'need_delete' => 1
                           ]
                       );
                       //写入缓存配置数据库
                       db('m3u8_setting')->insertGetId(
                           [
                               'time_added' => time(),
                               'vod_id' => $vodId,
                               'delete_start_index' => 0,
                               'number' => $data['ts_number'],
                               'delete_end_index' => $data['ts_offset'],
                           ]
                       );
                   }
               }
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                $this->error($e->getMessage(),null,$e->getTrace());
            }
            $this->success('操作成功！');

        } else {
            $xilie_id = input('xilie_id');
            $xilieInfo = db('explore')->where('id', $xilie_id)->find();
            if (empty($xilieInfo)) {
                $this->error('数据有误!');
            }
            $this->assign('xilieInfo', $xilieInfo);
            return $this->fetch('admin@explore/allm3u8');
        }
    }

}